package server;

import com.github.wenzi.servlet.HttpServlet;
import com.github.wenzi.servlet.HttpServletWapper;
import com.github.wenzi.servlet.Request;
import com.github.wenzi.servlet.Response;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * mapper组件
 */
public class Mapper {
    private List<Host> hosts;

    public Mapper() {
        this.hosts=new ArrayList<>();
    }

    /**
     * 添加虚拟主机
     * @param host
     */
    public void addHost(Host host) {
        hosts.add(host);
    }

    /**
     * 遍历虚拟主机查找合适的请求content;
     * @param request
     * @param response
     */
    public void doDispathRequest(Request request, Response response) throws Exception {
        for (Host host : hosts) {
            String url = request.getUrl();
            Content content = host.getContent();
            if(url.startsWith(content.getPath())){
                Map<String, HttpServletWapper> servletMap = content.getServletMap();
                if(servletMap.get(url) == null) {
                   response.outputHtml(request.getUrl());
                }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }

        }

    }
}
}
